<template>
    <el-container class="main-layout">
        <el-header class="header">
            <div class="logo-area">
                <img src="../assets/logo.png" alt="Logo" class="logo-img" />
                <span class="system-name">慧医数字医疗应用系统</span>
            </div>
        </el-header>
        <el-container>
            <el-aside width="200px" class="aside">
                <el-menu :default-active="$route.path" class="el-menu-vertical-demo" router>
                    <el-menu-item index="/">
                        <el-icon>
                            <House />
                        </el-icon>
                        <span>首页</span>
                    </el-menu-item>
                    <el-menu-item index="/companies">
                        <el-icon>
                            <OfficeBuilding />
                        </el-icon>
                        <span>医药公司管理</span>
                    </el-menu-item>
                    <el-menu-item index="/policies">
                        <el-icon>
                            <Document />
                        </el-icon>
                        <span>医药公司政策管理</span>
                    </el-menu-item>
                    <el-menu-item index="/doctors">
                    <el-icon>
                        <User />
                    </el-icon>
                    <span>医师管理</span>
                    </el-menu-item>

                    <el-menu-item index="/materials">
                        <el-icon>
                            <Box />
                        </el-icon>
                        <span>必备材料管理</span>
                    </el-menu-item>
                  <el-menu-item index="/cities">
                    <el-icon>
                      <Location />
                    </el-icon>
                    <span>城市管理</span>
                  </el-menu-item>
                </el-menu>
            </el-aside>
          <el-main class="main-content">
            <!-- 首页内容 -->
            <div v-if="$route.path === '/'">
              <!-- 第一行：统计卡片 -->
              <el-row :gutter="20">
                <el-col :span="6">
                  <StatCard title="医师数量" :value="stats.physicians" :loading="loading" />
                </el-col>
                <el-col :span="6">
                  <StatCard title="销售药品种类" :value="stats.drugsSold" :loading="loading" />
                </el-col>
                <el-col :span="6">
                  <StatCard title="合作企业" :value="stats.partnerCompanies" :loading="loading" />
                </el-col>
                <el-col :span="6">
                  <StatCard title="销售地点" :value="stats.salesLocations" :loading="loading" />
                </el-col>
              </el-row>

              <!-- 第二行：医师职称分布（单独一行） -->
              <el-row :gutter="20" class="chart-row">
                <el-col :span="24">
                  <el-card class="title-distribution-card">
                    <template #header>
                      <span>医师职称分布</span>
                      <el-button
                          v-if="titleDistributionError"
                          size="small"
                          type="text"
                          @click="fetchTitleDistribution"
                      >
                        重试
                      </el-button>
                    </template>
                    <div v-if="titleDistributionLoading" class="chart-loading">
                      <el-icon class="is-loading"><Loading /></el-icon>
                      数据加载中...
                    </div>
                    <div v-else-if="titleDistributionError" class="chart-error">
                      <el-empty description="数据加载失败">
                        <el-button type="primary" @click="fetchTitleDistribution">重新加载</el-button>
                      </el-empty>
                    </div>
                    <div
                        v-else
                        ref="titleChartRef"
                        class="title-chart"
                    ></div>
                  </el-card>
                </el-col>
              </el-row>

              <!-- 第三行：科室分布和政策信息 -->
              <el-row :gutter="20" class="bottom-row">
                <!-- 左侧：科室分布 -->
                <el-col :span="12">
                  <ChartCard
                      title="医院科室分布"
                      :option="pieChartOption"
                      :loading="deptLoading"
                      :error="deptError"
                      @retry="fetchDeptDistribution"
                  />
                </el-col>

                <!-- 右侧：政策信息 -->
                <el-col :span="12">
                  <el-card shadow="never" class="policy-card">
                    <template #header>
                      <div class="policy-header">
                        <span>最新医保/医药政策</span>
                        <el-button
                            link
                            type="primary"
                            @click="navigateToPolicyManagement"
                            class="more-button"
                        >
                          More
                          <el-icon><ArrowRight /></el-icon>
                        </el-button>
                      </div>
                    </template>
                    <ul class="policy-list">
                      <li v-for="policy in policies.medical" :key="policy.id">
                        {{ policy.title }}
                      </li>
                    </ul>
                  </el-card>
                </el-col>
              </el-row>
            </div>

            <!-- 其他页面内容 -->
            <router-view />
          </el-main>
        </el-container>
    </el-container>
</template>

<script setup>
import { useRouter } from 'vue-router'
import { ArrowRight } from '@element-plus/icons-vue'

const router = useRouter()

// 跳转到政策管理页面
const navigateToPolicyManagement = () => {
  router.push('/policies')
}
import { ref, onMounted, computed ,nextTick} from 'vue';
import axios from 'axios';
import * as echarts from 'echarts'
// 组件引入
import StatCard from '../components/StartCard.vue';
import ChartCard from '../components/ChartCard.vue';
/////////////////第一行动态数据
const stats = ref({
  physicians: 0,  // 初始值设为0
  drugsSold: 0,
  partnerCompanies: 0,
  salesLocations: 0
});

const loading = ref(false);

const fetchStats = async () => {
  loading.value = true;
  try {
    const response = await axios.get('/api/dashboard/stats');
    console.log('完整响应数据:', response.data); // 调试用

    // 关键修正点：正确访问stats嵌套数据
    if (response.data && response.data.stats) {
      stats.value = {
        physicians: Number(response.data.stats.physicians) || 0,
        drugsSold: Number(response.data.stats.drugsSold) || 0,
        partnerCompanies: Number(response.data.stats.partnerCompanies) || 0,
        salesLocations: Number(response.data.stats.salesLocations) || 0
      };
      console.log('成功更新stats:', stats.value); // 调试用
    } else {
      console.warn('响应缺少stats字段', response.data);
    }
  } catch (error) {
    console.error("请求失败:", {
      message: error.message,
      response: error.response?.data
    });
  } finally {
    loading.value = false;
  }
};
onMounted(() => {
  fetchStats();
  // 定期刷新数据
  setInterval(fetchStats, 60000); // 每分钟刷新一次
});
/////////第一行结束
/////////医生职称
const titleChartRef = ref(null)
let titleChartInstance = null
const titleDistribution = ref({}) // 存储 {职称:数量} 的映射

const error = ref(null)
const handleChartResize = () => {
  if (titleChartInstance) {
    titleChartInstance.resize()
  }
}
// 获取职称分布数据
const fetchTitleDistribution = async () => {
  loading.value = true
  error.value = null

  try {
    const response = await axios.get('/api/doctor-title/distribution')
    console.log('[1] 完整响应:', response.data)

    // 关键修正：正确提取data字段
    const responseData = response.data.data || {}
    console.log('[2] 有效数据:', responseData)

    titleDistribution.value = responseData

    // 确保DOM已渲染
    await nextTick()

    if (!titleChartRef.value) {
      console.error('错误: 图表容器未找到!')
      return
    }

    // 检查容器尺寸
    console.log('[3] 容器尺寸:', {
      width: titleChartRef.value.clientWidth,
      height: titleChartRef.value.clientHeight
    })

    if (!titleChartInstance) {
      titleChartInstance = echarts.init(titleChartRef.value)
      window.addEventListener('resize', handleChartResize)
    }

    const option = createTitleChartOption(titleDistribution.value)
    console.log('[4] 图表配置:', option)
    titleChartInstance.setOption(option)

  } catch (err) {
    console.error('[错误] 获取数据失败:', err)
    error.value = err
  } finally {
    loading.value = false
  }
}
/**
 * 创建ECharts配置
 * @param {Object} dataMap - {职称: 数量} 的映射
 */
const createTitleChartOption = (dataMap) => {
  // 过滤掉非职称字段 (code/message等)
  const validEntries = Object.entries(dataMap)
      .filter(([key]) => !['code', 'message', 'reportTime'].includes(key))

  // 按数量降序排序
  const sortedEntries = validEntries.sort((a, b) => b[1] - a[1])

  const titles = sortedEntries.map(entry => entry[0])
  const counts = sortedEntries.map(entry => entry[1])

  console.log('[图表数据] 有效职称:', titles)
  console.log('[图表数据] 对应数量:', counts)

  return {
    title: {
      text: '医师职称分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      formatter: '{b}: {c}人'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: titles,
      axisLabel: {
        interval: 0,
        rotate: 30
      }
    },
    yAxis: {
      type: 'value',
      name: '人数'
    },
    series: [{
      type: 'bar',
      data: counts,
      itemStyle: { color: '#409EFF' },
      label: { show: true }
    }]
  }
}
// 组件挂载时获取数据
onMounted(() => {
  console.log('组件已挂载，开始获取数据...')
  fetchTitleDistribution()

  // 确保这行代码被执行
  console.log('组件已挂载')
})
////////////////////////////科室
const deptLoading = ref(false)
const deptError = ref(null)
const pieChartOption = ref(getDefaultChartOption()
)

function getDefaultChartOption() {
  return {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center'
    },
    series: [{
      name: '科室分布',
      type: 'pie',
      radius: ['40%', '70%'],
      data: [{ name: '数据加载中...', value: 1 }],
      itemStyle: {
        borderRadius: 10,
        borderColor: '#fff',
        borderWidth: 2
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
}
// 获取科室分布数据
const fetchDeptDistribution = async () => {
  deptLoading.value = true
  deptError.value = null

  try {
    const res = await axios.get('/api/departments/distribution')

    // 数据校验
    if (!res.data?.data) {
      throw new Error('无效的数据格式')
    }

    // 转换数据格式
    const seriesData = Object.entries(res.data.data)
        .map(([name, value]) => ({
          name: name || '未分类科室',
          value: Number(value) || 0
        }))
        .filter(item => item.value > 0) // 过滤零值数据

    // 更新图表配置
    pieChartOption.value = {
      ...pieChartOption.value,
      series: [{
        ...pieChartOption.value.series[0],
        data: seriesData.length ? seriesData : [{ name: '暂无数据', value: 1 }]
      }]
    }

  } catch (error) {
    console.error('科室数据加载失败:', error)
    deptError.value = error

    // 显示错误状态
    pieChartOption.value = {
      ...pieChartOption.value,
      series: [{
        ...pieChartOption.value.series[0],
        data: [{ name: '数据加载失败', value: 1 }]
      }]
    }

    // 开发环境显示详细错误
    if (import.meta.env.DEV) {
      ElMessage.error(`加载失败: ${error.message}`)
    }
  } finally {
    deptLoading.value = false
  }
}

// 创建饼图配置
const createPieChartOption = (data) => {
  // 防御式编程：处理undefined/null/非对象值
  const safeData = data && typeof data === 'object' ? data : {};

  // 转换数据格式
  const seriesData = Object.entries(safeData)
      .map(([name, value]) => ({
        name: name || '未命名科室',
        value: Number(value) || 0
      }))
      .filter(item => item.value > 0); // 过滤掉值为0的项

  return {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: seriesData.map(item => item.name) // 确保legend数据同步
    },
    series: [{
      name: '科室分布',
      type: 'pie',
      radius: ['40%', '70%'],
      data: seriesData.length ? seriesData : [{ name: '暂无数据', value: 1 }],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  };
}

// 初始化数据
onMounted(() => {
  console.log('组件已挂载，开始获取数据...')
  fetchDeptDistribution()
  console.log('饼图ing...')
  createPieChartOption()
})
/////////////////////////

const policies = ref({
  medical: [
    { id: 1, title: '2023年医保药品目录更新通知' },
    { id: 2, title: '关于调整部分药品报销比例的通知' },
    { id: 3, title: '门诊慢性病用药管理新规' },
    { id: 4, title: '国家基本药物目录调整公告' },
    { id: 5, title: '医保电子凭证应用推广通知' },
  ],
  company: [
    { id: 1, title: '医药企业合规经营管理办法' },
    { id: 2, title: '关于药品集中采购的新规定' },
    { id: 3, title: '医药代表备案管理要求' },
    { id: 4, title: '药品网络销售监管新规' },
    { id: 5, title: '药品上市许可持有人指南' }, ,
  ]
});



// 图表配置
const barChartOption = computed(() => ({
  tooltip: {},
  grid: { top: '15%', right: '5%', bottom: '15%', left: '15%' },
  xAxis: {
    type: 'category',
    data: physicianTitles.value.categories,
    axisLabel: {
      rotate: 0,
      fontSize: 12
    }
  },
  yAxis: { type: 'value' },
  series: [{
    data: physicianTitles.value.values,
    type: 'bar',
    itemStyle: {
      color: '#409EFF'
    },
    barWidth: '40%'
  }]
}));


// 模拟API请求
const fetchData = async () => {
  loading.value = true;
  try {
    // 这里应该是实际的API请求
    // 示例: const response = await axios.get('/api/dashboard');
    // 这里我们直接使用模拟数据
    await new Promise(resolve => setTimeout(resolve, 800));
  } catch (error) {
    console.error("数据加载失败:", error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.main-layout {
  height: 100vh;
}

.header {
  background-color: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  padding: 0 20px;
}

.logo-area {
  display: flex;
  align-items: center;
}

.logo-img {
  width: 40px;
  height: 40px;
  margin-right: 15px;
}

.system-name {
  font-size: 20px;
  font-weight: bold;
}

.aside {
  border-right: 1px solid #e6e6e6;
}

.policy-card {
  height: 100%;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

h3 {
  margin-top: 0;
  margin-bottom: 20px;
  font-weight: 600;
  color: #303133;
}

.policy-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.policy-list li {
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  font-size: 14px;
}

.policy-list li:last-child {
  border-bottom: none;
}

.policy-list li:hover {
  color: #409EFF;
  cursor: pointer;
}
.grid-cell {
  padding: 24px; /* 增大内边距 */
  height: 500px; /* 固定高度 */
}
.chart-row {
  margin-top: 20px;
}

.title-distribution-card {
  margin-bottom: 20px;
}

.title-chart {
  width: 100%;
  height: 350px;
}

.bottom-row {
  margin-top: 20px;
}

.policy-card {
  height: 100%;
}

.policy-list {
  padding-left: 20px;
}

.policy-list li {
  margin-bottom: 10px;
  list-style-type: disc;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .bottom-row .el-col {
    width: 100% !important;
  }
}
.policy-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.more-button {
  padding: 0;
  height: auto;
}

.policy-item {
  cursor: pointer;
  transition: color 0.3s;
  padding: 8px 0;
}

.policy-item:hover {
  color: #409EFF;
}
</style>